package com.example.studydemo.customview

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Path
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import androidx.core.content.ContextCompat
import androidx.core.graphics.drawable.toBitmap
import com.example.studydemo.R
import kotlin.random.Random

class FindView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {
    private val findBitmap =
        ContextCompat.getDrawable(context, R.drawable.ic_baseline_control_camera_24)
            ?.toBitmap(300, 300)

    private var findX = 0f
    private var findY = 0f
    private fun randomPosition() {
        findX = Random.nextInt(width - 300).toFloat()
        findY = Random.nextInt(height - 300).toFloat()
    }

    private val path = Path()
    private val paint = Paint().apply {
        style = Paint.Style.FILL
        color = Color.GRAY
    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        canvas?.apply {
            findBitmap?.let {
                drawBitmap(it, findX, findY, null)
            }
            drawPath(path, paint)
        }
    }

    override fun onTouchEvent(event: MotionEvent?): Boolean {
        event?.apply {
            when (action) {
                MotionEvent.ACTION_DOWN -> {
                    randomPosition()
                    path.reset()
                    path.addRect(0f, 0f, width.toFloat(), height.toFloat(), Path.Direction.CW)
                    path.addCircle(x, y, 200f, Path.Direction.CCW)
                }
                MotionEvent.ACTION_MOVE -> {
                    path.reset()
                    path.addRect(0f, 0f, width.toFloat(), height.toFloat(), Path.Direction.CW)
                    path.addCircle(x, y, 200f, Path.Direction.CCW)
                }
                MotionEvent.ACTION_UP -> {
                    path.reset()
                }
            }
            invalidate()
        }
        invalidate()
        performClick()
        return true
    }

    override fun performClick(): Boolean {
        return super.performClick()
    }
}